#include "sensor3worker.h"
#include "qthread.h"
#include <QDateTime>

Sensor3Worker::Sensor3Worker(ushort di, ushort d0, int startCount, int endCount, QObject *parent)
    : SensorWorker(di, d0, parent),
    m_startCount(startCount),
    m_endCount(endCount) {}

void Sensor3Worker::stop()
{
    m_running = false;
}

void Sensor3Worker::process()
{
    clearInputEdge();

    while (m_running) {
        ushort level = 0;
        if (checkInputLevel(level) && level < 1) {
            handleSignal();
        }
        QThread::msleep(1);
    }
    emit finished();
}

void Sensor3Worker::handleSignal()
{
    emit log("[" + QDateTime::currentDateTime().toString() +
             "] [DI]" + QString::number(m_di) + " : Signal detected");

    long encoder_count = getEncoderCount();
    long targetCount = encoder_count + m_startCount;

    // 等待编码器计数到达
    waitForEncoderCount(targetCount);
    if (!m_running) return;

    // 设置输出
    setOutputBit(0);
    emit log("[" + QDateTime::currentDateTime().toString() +
             "] [DO]" + QString::number(m_do) + " : Output started");

    // 等待信号结束
    ushort inputLevel = 0;
    while (inputLevel < 1 && m_running) {
        checkInputLevel(inputLevel);
        QThread::msleep(1);
    }
    if (!m_running) return;

    emit log("[" + QDateTime::currentDateTime().toString() +
             "] [DI]" + QString::number(m_di) + " : Signal ended");

    // 获取当前编码器位置
    encoder_count = getEncoderCount();
    targetCount = encoder_count + m_endCount;

    // 等待结束计数
    waitForEncoderCount(targetCount);
    if (!m_running) return;

    // 关闭输出
    setOutputBit(0xFFFF);
    emit log("[" + QDateTime::currentDateTime().toString() +
             "] [DO]" + QString::number(m_do) + " : Output stopped");
}
